package org.openjava.utils;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.openjava.model.Contact;
import org.openjava.model.People;
 

public class BeanUtils {
	public static Map<Object, Object> buildMap(Object obj,KeyValue keyValue){
		Map<Object,Object> map = new HashMap<Object, Object>();
		keyValue.fillMap(map);
		return map;
	}
	
	public void test() throws Exception {
		final org.openjava.model.Contact contact = new org.openjava.model.Contact();
		contact.setAddress("12345");
		contact.setTelephone("123456678");
		contact.setZipcode("323300");
		Map<Object,Object> map = buildMap(contact,new KeyValue(){

			public void fillMap(Map<Object, Object> map) {
				Object[] objs = new Object[]{contact};
				fillMapFromBeans(objs, "address", map);
			}
		});
		Iterator<Object>  keyIterator = map.keySet().iterator();
		while(keyIterator.hasNext()){
			Object obj = keyIterator.next();
			System.out.println(obj + " : " + map.get(obj));
		}
	}
	
	public static void fillMapFromBeans(Object[] objs,String keyProperty,Map<Object,Object> map){
		
		for(Object obj:objs){
			Object aobj = ReflectionUtils.getProperty(obj, keyProperty);
			map.put(aobj, obj);
		}
	}
	
	public static Object getDeepProperty(Object obj,String el){
		String[] strs = el.split("\\.");
		return getEndProperty(obj,strs,0);
	}
	
	private static Object getEndProperty(Object obj,String[] strs,int i){
		Object object = null;
		String methodName = strs[i];
		int index = -1;
		String intStr = "";
		if((index = methodName.indexOf("[")) != -1){
			int right = methodName.indexOf("]");
			index = Integer.parseInt(intStr = methodName.substring(index+1,right));
			methodName = methodName.substring(0, methodName.length() - intStr.length() -2);
		}
		try{
			object = ReflectionUtils.invokeMethodByName(obj, "get" + StringUtils.capitalize(methodName));
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
		if(object.getClass().isArray()){
			object = ArrayUtils.getElByIndex(object, index);
		}
		if(strs.length == i +1){
			return object;
		}
		return getEndProperty(object,strs,++i);
	}
	
	public void testGetDeepProperty() throws Exception {
		Contact contact = new  Contact();
		contact.setAddress("234");
		contact.setTelephone("12323");
		contact.setZipcode("323300");
		People p = new  People();
		p.setAge(22);
		p.setContact(contact);
		p.setDate(new Date());
		p.setName("LeiTing");
		p.setSex("male");
		p.setTest(new int[]{1,2,3});
		
		System.out.println(getDeepProperty(p, "test[2]"));
	}
}

